//
//  ZCComposeTextView.swift
//  weibo
//
//  Created by Ning Xie on 16/8/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class ZCComposeTextView: UITextView {

    
    private lazy var placeHolderLabel: UILabel = {
       
        let label = UILabel()
        label.numberOfLines = 0
//        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.lightGrayColor()
        label.sizeToFit()
        return label
    }()
    
     var placeHolder:String?{
        didSet{
            
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont?{
        didSet{
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    override var text: String?{
        didSet{
            placeHolderLabel.hidden = hasText()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        
        autocorrectionType = .No
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0))
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZCComposeTextView.textViewTextDidChange), name: UITextViewTextDidChangeNotification, object: nil)
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 7
    }
    
    @objc private func textViewTextDidChange(){
        
        placeHolderLabel.hidden = hasText()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}
